﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Ext.Net.MVC;
using Sharp.Portal.Other;

namespace Sharp.Portal.ExtNet
{
    /// <summary>
    /// 列定义
    /// </summary>
    public class ExtColumn : ISharpColumn
    {
        #region 获取模型的列定义

        /// <summary>
        /// 获取模型的列定义
        /// </summary>
        /// <returns></returns>
        public Dictionary<PropertyInfo, ListModelInfo> GetColumnInfos(Type dic)
        {
            var outPut = new Dictionary<PropertyInfo, ListModelInfo>();
            foreach (var property in dic.GetProperties())
            {
                var attributy =
                  property.GetCustomAttributes(typeof(ColumnBaseAttribute), true).FirstOrDefault() as ColumnBaseAttribute;
                if (attributy == null) continue;

                ColumnAttribute column;
                if (attributy is Ext.Net.MVC.NumberColumnAttribute)
                {
                    column = new NumberColumnAttribute();
                }
                else if (attributy is Ext.Net.MVC.TemplateColumnAttribute)
                {
                    column = new TemplateColumnAttribute();
                }
                else if (attributy is Ext.Net.MVC.DateColumnAttribute)
                {
                    column = new DateColumnAttribute();
                }
                else if (attributy is Ext.Net.MVC.BooleanColumnAttribute)
                {
                    var attr = attributy as Ext.Net.MVC.BooleanColumnAttribute;
                    column = new BooleanColumnAttribute(attr.TrueText, attr.FalseText);
                }
                else
                {
                    column = new Sharp.Portal.ColumnAttribute();
                }

                column.Align = (Alignment)Enum.Parse(typeof(Alignment), attributy.Align.ToString());
                column.DataIndex = attributy.DataIndex;
                column.Hidden = attributy.Hidden;
                column.Locked = attributy.Locked;
                column.Order = attributy.Order;
                column.Sortable = attributy.Sortable;
                column.Text = attributy.Text;
                column.Width = attributy.Width;



                var queryOption = property.GetCustomAttributes(typeof(QueryOptionAttribute), false).FirstOrDefault() as QueryOptionAttribute ?? new QueryOptionAttribute();
                outPut.Add(property, new ListModelInfo()
                {
                    Attribute = column,
                    Order = column.Order,
                    QueryOption = queryOption.Option
                });
            }

            outPut = outPut.OrderBy(x => x.Value.Order)//.ThenByDescending(x => x.Key)
                .ToDictionary(k => k.Key, v => v.Value);

            return outPut;
        }

        #endregion
    }
}
